package com.logisticsrepair.util.stpInterface;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.logisticsrepair.customEntity.UserRolePermissionEntity;
import com.logisticsrepair.entity.PermissionEntity;
import com.logisticsrepair.entity.UserRoleEntity;
import com.logisticsrepair.mapper.PermissionMapper;
import com.logisticsrepair.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 */
@Component    // 保证此类被SpringBoot扫描，完成Sa-Token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 返回指定账号id所拥有的权限码集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 该账号id具有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        String roleId = userRoleMapper.selectOne(new LambdaQueryWrapper<>(new UserRoleEntity()).eq(UserRoleEntity::getUserId, loginId.toString())).getRoleId();
        List<PermissionEntity> permissionEntities = permissionMapper.queryAllByRoleId(roleId);
        List<String> list = new ArrayList<String>();
        for (PermissionEntity entity : permissionEntities) {
            list.add(entity.getPermName());
        }
        return list;
    }

    /**
     * 返回指定账号id所拥有的角色标识集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 该账号id具有的角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> list = new ArrayList<String>();
        UserRolePermissionEntity rolePermission = userRoleMapper.queryUserRoleByUserId(loginId.toString());
        if (rolePermission == null || rolePermission.getUserType() == null) {
            return list;
        }
        list.add(rolePermission.getUserType());
        this.getPermissionList(loginId, loginType);
        return list;
    }
}
